package com.recipedb.sprint.repository;

import com.recipedb.sprint.entity.Users;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.Optional;

@Repository
public interface UsersRepository extends JpaRepository<Users, Long> {
    //按用户名查询用户（用于登录）
    Optional<Users> findByUsername(String username);

    //按手机号查询用户（用于注册/登录/找回密码）
    Optional<Users> findByPhone(String phone);

    //校验手机号是否呗其他用户占用（更新手机号）
    boolean existsByPhoneAndUseridNot(String phone, Long userid);

    Long countByCreatedAtAfter(LocalDateTime Time);


    @Modifying
    @Transactional
    @Query(value = "INSERT INTO users (created_at, password, phone, preferences, updated_at, username) " +
            "VALUES (:createdAt, :password, :phone, CAST(:preferences AS jsonb), :updatedAt, :username)",
            nativeQuery = true)
    void saveWithJsonb(
            @Param("createdAt") LocalDateTime createdAt,
            @Param("password") String password,
            @Param("phone") String phone,
            @Param("preferences") String preferences,  // 这里参数名必须是 "preferences"
            @Param("updatedAt") LocalDateTime updatedAt,
            @Param("username") String username
    );

    // 新增：自定义更新方法（带 jsonb 转换）
    @Modifying
    @Transactional
    @Query(value = "UPDATE users " +
            "SET username = :username, " +
            "preferences = CAST(:preferences AS jsonb), " +  // 关键：显式转为 jsonb
            "updated_at = :updatedAt " +
            "WHERE userid = :userid",
            nativeQuery = true)
    void updateUserWithJsonb(
            @Param("userid") Long userid,
            @Param("username") String username,
            @Param("preferences") String preferences,  // 传入 JSON 字符串
            @Param("updatedAt") LocalDateTime updatedAt
    );

}
